<template>
  <div @click="handleOpenPop" class="datePicker">
    <img
      width="26px"
      height="26px"
      src="@/assets/image/mine/icon／missionlist／filter／timeFilter@2x.png"
      alt=""
    />
    <span>{{ format(props.modelValue, props.format) }}</span>
    <span class="iconfont icon-arrow-down ml-4">
      <el-icon v-show="show"><CaretTop /></el-icon>
      <el-icon v-show="!show"><CaretBottom /></el-icon>
    </span>
  </div>
  <div class="box-date" v-show="show">
    <div class="date-picker-container">
      <div class="close-button" @click="handleOpenPop">
        <el-icon><CloseBold /></el-icon>
      </div>
      <div class="date-title">
        <p class="title-text">选择</p>
        <p class="title-desc">建议您从最近的可选日期开始创建</p>
      </div>

      <div class="date-part">
        <div class="date-picker">
          <div class="date-picker-active"></div>
          <div
            class="picker-column"
            ref="yearColumn"
            @scroll="onScroll('year')"
          >
            <ul>
              <li
                v-for="(year, index) in years"
                :key="index"
                :class="{ active: index === selectedYearIndex }"
              >
                <span v-if="year">{{ year }}年</span>
              </li>
            </ul>
          </div>
          <div
            class="picker-column"
            ref="monthColumn"
            @scroll="onScroll('month')"
          >
            <ul>
              <li
                v-for="(month, index) in months"
                :key="index"
                :class="{ active: index === selectedMonthIndex }"
              >
                <span v-if="month"> {{ month }}月</span>
              </li>
            </ul>
          </div>
          <div class="picker-column" ref="dayColumn" @scroll="onScroll('day')">
            <ul>
              <li
                v-for="(day, index) in days"
                :key="index"
                :class="{ active: index === selectedDayIndex }"
              >
                <span v-if="day"> {{ day }}日</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="date-picker-bottom">
        <div @click="handleReset" class="button reset">重置</div>
        <div @click="curDateValueChange" class="button confirm">确认选择</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { format, add, startOfWeek, subDays, getDaysInMonth } from "date-fns";
import { CaretTop, CaretBottom, CloseBold } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";

const years = ref([]);
const months = ref([]);
const days = ref([]);

const selectedYearIndex = ref(0);
const selectedMonthIndex = ref(0);
const selectedDayIndex = ref(0);

// 模拟数据，实际应根据需求生成
const generateYears = () => {
  const currentYear = new Date().getFullYear();
  return [
    "",
    "",
    ...Array.from({ length: 10 }, (_, index) => currentYear - 5 + index),
    "",
    "",
  ];
};

const generateMonths = () => {
  return [
    "",
    "",
    ...Array.from({ length: 12 }, (_, index) => index + 1),
    "",
    "",
  ];
};
const generateDays = () => {
    let curMonth = months.value[selectedMonthIndex.value];
    let curYear = years.value[selectedYearIndex.value];
    let len =  getDaysInMonth(new Date(curYear, curMonth-1));
  return [
    "",
    "",
    ...Array.from({ length: len }, (_, index) => index + 1),
    "",
    "",
  ];
};

// 初始化数据
years.value = generateYears();
months.value = generateMonths();
// days.value = generateDays();

const initDatePickerIndex = () => {
  const currentDate = props.modelValue;
  let curYear = new Date(currentDate).getFullYear();
  let curMonth = new Date(currentDate).getMonth() + 1;
  let curDay = new Date(currentDate).getDate();
  selectedYearIndex.value = years.value.findIndex(dd => dd === curYear);
  selectedMonthIndex.value = months.value.findIndex(dd => dd === curMonth);
  days.value = generateDays();
  selectedDayIndex.value = days.value.findIndex(dd => dd === curDay);
  nextTick(() => {
    yearColumn.value.scrollTop = (selectedYearIndex.value - 2) * 56;
    monthColumn.value.scrollTop = (selectedMonthIndex.value - 2) * 56;
    dayColumn.value.scrollTop = (selectedDayIndex.value - 2) * 56;
  });
};
// 定义延时处理函数
let scrollTimeout = null;

const onScroll = (type) => {
  let column = null;
  switch (type) {
    case "year":
      column = yearColumn.value;
      break;
    case "month":
      column = monthColumn.value;
      break;
    case "day":
      column = dayColumn.value;
      break;
  }

  // 清除之前的定时器
  if (scrollTimeout) {
    clearTimeout(scrollTimeout);
  }

  // 设置新的定时器来延迟处理
  scrollTimeout = setTimeout(() => {
    // 防止滚动条跳动
    if (column.scrollTop % 56 !== 0) {
      column.scrollTop = Math.round(column.scrollTop / 56) * 56;
    }

    // 更新选中索引
    const selectedIndex = Math.round(column.scrollTop / 56) + 2; // 假设每行高度为56px
    switch (type) {
      case "year":
        selectedYearIndex.value = selectedIndex;
        days.value = generateDays();
        break;
      case "month":
        selectedMonthIndex.value = selectedIndex;
        days.value = generateDays();
        break;
      case "day":
        selectedDayIndex.value = selectedIndex;
        break;
    }
  }, 100); // 设置一个适当的延时，例如100ms
};
const yearColumn = ref();
const monthColumn = ref();
const dayColumn = ref();

// 初次加载时居中选中项
onMounted(() => {
//   initDatePickerIndex();
//   nextTick(() => {
//     // yearColumn.value.scrollTo({
//     //   top: selectedYearIndex.value * 56,
//     //   behavior: "smooth",
//     // });
//   });
});
const props = defineProps({
  modelValue: {
    type: Date,
    default: new Date(),
  },
  format: {
    type: String,
    default: "yyyy年MM月dd日",
  },
  formatValue: {
    type: String,
    default: "yyyy-MM-dd",
  },
});
const emits = defineEmits(["update:modelValue", "confirm"]);
const show = ref(false);
const value = ref(new Date());
const handleOpenPop = () => {
  show.value = !show.value;
  if(show.value){
    initDatePickerIndex();
  }
};
const curDateValueChange = () => {
    let year = years.value[selectedYearIndex.value];
    let month = months.value[selectedMonthIndex.value];
    let day = days.value[selectedDayIndex.value];
    emits("update:modelValue", format(new Date(year, month-1, day), props.formatValue));
    show.value = false;
    emits("confirm");
}
const handleReset = () => {
    initDatePickerIndex();
}
</script>

<style lang="scss" scoped>
.datePicker {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-family: Komu A, Komu A;
  font-weight: normal;
  font-size: 14px;
  color: #666666;
  position: relative;
}
.box-date {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  top: 0;
  left: 0;
  .date-picker-container {
    width: 100%;
    height: 450px;
    background: #ffffff;
    border-radius: 12px 12px 0px 0px;
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    padding-top: 20px;
    box-sizing: border-box;
    .close-button {
      position: absolute;
      right: 16px;
      top: 20px;
      width: 24px;
      height: 24px;
      background: #e6e6e6;
      border-radius: 50%;
      color: #666666;
      font-size: 12px;
      text-align: center;
      line-height: 28px;
    }
    .date-title {
      .title-text {
        font-weight: bold;
        font-size: 16px;
        color: #333333;
      }
      .title-desc {
        font-size: 12px;
        color: #666666;
        margin-top: 20px;
      }
      p {
        margin: 0 auto;
        text-align: center;
      }
    }
    .date-picker-bottom {
      width: 100%;
      height: 83px;
      background: #ffffff;
      box-shadow: 0px -4px 8px 0px rgba(0, 0, 0, 0.2);
      border-radius: 0px 0px 0px 0px;
      position: absolute;
      bottom: 0;
      display: flex;
      justify-content: center;
      .button {
        width: 160px;
        height: 40px;
        border-radius: 8px;
        text-align: center;
        line-height: 40px;
        font-weight: 500;
        font-size: 14px;
        margin-top: 5px;
      }
      .reset {
        border: 1px solid #4560e6;
        color: #4560e6;
      }
      .confirm {
        background: #4560e6;
        color: #ffffff;
        margin-left: 15px;
      }
    }
    .date-part {
      flex: 1;
      height: 0;
      .date-picker {
        display: flex;
        justify-content: space-around;
        height: 280px; /* 根据实际需求调整高度 */
        overflow: hidden;
        position: relative;
        padding: 0 26px;
        box-sizing: border-box;
        .date-picker-active {
          width: calc(100% - 52px);
          height: 40px;
          background: rgba(69, 96, 230, 0.1);
          border-radius: 4px 4px 4px 4px;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .picker-column {
        position: relative;
        z-index: 2;
        flex: 1;
        overflow-y: scroll;
        font-weight: bold;
        font-size: 16px;
        color: #999999;
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* IE 10+ */
        &::-webkit-scrollbar {
          width: 0;
          height: 0;
        }
      }

      ul {
        list-style: none;
        padding: 0;
        margin: 0;
      }

      li {
        height: 40px; /* 根据实际需求调整每行高度 */
        line-height: 40px;
        text-align: center;
        padding: 8px 0;
      }

      li.active {
        color: #4560e6;
      }
    }
  }
}
</style>
